package com.yuzhenxin.bookstore.web.servlet;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.example.framework.common.exception.ServiceException;
import com.yuzhenxin.bookstore.domain.Cart;
import com.yuzhenxin.bookstore.domain.User;
import com.yuzhenxin.bookstore.service.UserService;
import com.yuzhenxin.bookstore.tools.commons.CommonUtils;
import com.yuzhenxin.bookstore.tools.mail.Mail;
import com.yuzhenxin.bookstore.tools.mail.MailUtils;
import com.yuzhenxin.bookstore.tools.servlet.BaseServlet;
import jakarta.mail.MessagingException;
import jakarta.mail.Session;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.MessageFormat;
import java.util.Objects;
import java.util.Properties;

/**
 * User表述层
 */
@WebServlet("/UserServlet")
public class UserServlet extends BaseServlet {

    private final UserService userService = new UserService();

    /**
     * 注册功能
     */
    public String register(HttpServletRequest request) throws IOException {
        //封装表单数据
        User form = BeanUtil.toBean(request.getParameterMap(), User.class);
        //补全
        form.setUid(UUID.fastUUID().toString());
        form.setCode(UUID.fastUUID().toString());
        String username = form.getUsername();
        String password = form.getPassword();
        if (password.length() < 3 || password.length() > 15 || username.length() < 3
                || username.length() > 15) {
            request.setAttribute("form", form);
            request.getSession().setAttribute("errors2", "Regist failed!");
            return "r:/jsps/user/index.jsp";
        }
        try {
            userService.regist(form);
        } catch (ServiceException e) {
            request.setAttribute("msg", e.getMessage());
            request.setAttribute("form", form);
            return "r:/jsps/user/index.jsp";
        }
        //获取配置文件内容
        Properties props = new Properties();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                Objects.requireNonNull(this.getClass().getClassLoader().getResourceAsStream(
                        "email_template.properties"))));
        props.load(br);
        String host = props.getProperty("host");
        String uname = props.getProperty("uname");
        String pwd = props.getProperty("pwd");
        String from = props.getProperty("from");
        String to = form.getEmail();
        String subject = props.getProperty("subject");
        String content = props.getProperty("content");
        content = MessageFormat.format(content, form.getCode());//替换{0}

        Session session = MailUtils.createSession(host, uname, pwd);
        Mail mail = new Mail(from, to, subject, content);
        try {
            MailUtils.send(session, mail);
        } catch (MessagingException e) {
            request.setAttribute("msg", e.getMessage());
        }

        /*
         * 1、保存成功信息 2、转发到msg.jsp
         */
        request.setAttribute("msg", "Congratulations, registration is successful, please email activation!");
        return "f:/jsps/msg.jsp";
    }

    public String active(HttpServletRequest request) {
        String code = request.getParameter("code");
        try {
            userService.active(code);
            request.setAttribute("msg", "Activation successful, please login!");
        } catch (ServiceException e) {
            request.setAttribute("msg", e.getMessage());
        }
        return "f:/jsps/msg.jsp";
    }

    public String login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        User form = CommonUtils.toBean(request.getParameterMap(), User.class);
        try {
            User user = userService.login(form);
            request.getSession().setAttribute("session_user", user);
            // 给用户添加购物车，向session保存一个Cart对象
            request.getSession().setAttribute("cart", new Cart());
            return "r:/main.jsp";
        } catch (ServiceException e) {
            request.getSession().setAttribute("errors1", "Incorrect username or password!");
            request.setAttribute("msg", e.getMessage());
            request.setAttribute("form", form);
            return "r:/jsps/user/index.jsp";
        }
    }

    public String quit(HttpServletRequest request) {
        request.getSession().invalidate();
        return "r:/main.jsp";
    }

    public String changePassword(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        try {
            userService.change(username, password);
            return "r:/main.jsp";
        } catch (ServiceException e) {
            response.getWriter().print("""
                    <script language="JavaScript">
                    \talert("Invalid username!");
                    </script>
                    """);
            return "r:/jsps/user/change.jsp";
        }
    }
}
